﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;

namespace OSS
{
    public class Tools
    {
        public static string SaveImage(string base64,string imgurl)
        {
            if (base64.IndexOf(',') == -1)
            {
                return base64;
            }
            DirectoryInfo info = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/Content/Image/" + imgurl));
            if (!info.Exists)
            {
                info.Create();
            }
            //切割 base64 数据源
            var data = base64.Split(',')[1];
            //获取图片格式
            var exname = "." + base64.Split(';')[0].Split('/')[1];
            if (exname == ".jpg" || exname == ".jpeg" || exname == ".png" || exname == ".gif" || exname == ".bmp")
            {
                //将base64编码转成字节
                byte[] buffer = Convert.FromBase64String(data);
                //将字节转换成流
                MemoryStream ms = new MemoryStream(buffer);
                //将流转换成图
                Image image = Image.FromStream(ms);
                //随机名称
                string name = Guid.NewGuid().ToString().Split('-')[0] + exname;
                string path = HttpContext.Current.Server.MapPath("~/Content/Image/"+imgurl+"/" + name);
                //保存图片
                image.Save(path);
                return name;
            }
            else
            {
                return null;
            }
        }
        public static string GetQueryString()
        {
            using (Stream postData = HttpContext.Current.Request.InputStream)
            {
                using (StreamReader sRead = new StreamReader(postData, System.Text.Encoding.UTF8))
                {
                    return sRead.ReadToEnd();
                }
            }
        }
    }
}